/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session;

import entity.Construct;
import entity.Player;
import entity.ProductionCost;
import java.util.Collection;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import session.manager.CheckBeanLocal;
import session.manager.ConstructManagerBeanLocal;
import session.manager.PlayerManagerBeanLocal;
import session.manager.ResourceManagerBeanLocal;
import session.timed.ProductionTimedBeanLocal;

/**
 *
 * @author antonio
 */
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class ResourcesProducerBean implements ResourcesProducerBeanLocal {
    
    @EJB
    private PlayerManagerBeanLocal playerManager;
    
    @EJB
    private ConstructManagerBeanLocal constructManager;
    
    @EJB
    private ResourceManagerBeanLocal resourceManager;
    
    @EJB
    private CheckBeanLocal checkBean;
    
    @EJB
    private ProductionTimedBeanLocal timedBean;

    @Override
    public boolean produce(String username, String constructName, int amount) {
        if(username == null || constructName == null || amount <= 0) {
            throw new IllegalArgumentException();
        }
        Construct construct = constructManager.findConstruct(constructName);
        if(checkBean.checkConstruct(username, constructName, amount) &&
            checkBean.checkProductionCost(username, constructName, amount)) {
            Collection<ProductionCost> productionCosts = construct.getProductionCostCollection();
            for (ProductionCost p : productionCosts) {
                resourceManager.decrese(username, p.getResource1().getName(), p.getAmount() * amount);
            }
            constructManager.occupiesConstructs(username, constructName, amount);
            timedBean.initTimer(username, constructName, amount);
            return true;
        }    
        return false;
    }

}
